package com.pirestupppai.imagetool.filtertool;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.View;

import com.pirestupppai.common.Constant;
import com.pirestupppai.utils.Utils;

/**
 *  滤镜View
 */

public class FilterView extends View{
    private Context mContext;
    private int surplusHeight;              // 当前屏幕剩余高度
    private float scaleRate;                // 图片缩放比例
    private Matrix mBackgroundMatrix;       // 图片缩放matrix
    private Bitmap mBackgroundBitmap;       // 原始Bitmap

    public FilterView(Context context){
        this(context, null);
        this.mContext = context;
        init();

    }

    public FilterView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        this.mContext = context;
        init();
    }

    private void init() {
        surplusHeight = Constant.HEIGHT_OF_SCREEN - Constant.HEIGHT_OF_STATUSBAR
                - Utils.dpToPx(mContext, 64) - Utils.dpToPx(mContext, 85);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        mBackgroundMatrix = new Matrix();
        if (mBackgroundBitmap != null) {
            float surplusRate = (float) Constant.WIDTH_OF_SCREEN / (float) surplusHeight;
            float pictureRate = (float) mBackgroundBitmap.getWidth() / (float) mBackgroundBitmap.getHeight();
            if (pictureRate > surplusRate) {
                scaleRate = (float) Constant.WIDTH_OF_SCREEN / (float) mBackgroundBitmap.getWidth();
                setMeasuredDimension(Constant.WIDTH_OF_SCREEN, Constant.WIDTH_OF_SCREEN * mBackgroundBitmap.getHeight() / mBackgroundBitmap.getWidth());
            } else {
                scaleRate = (float) surplusHeight / (float) mBackgroundBitmap.getHeight();
                setMeasuredDimension(surplusHeight * mBackgroundBitmap.getWidth() / mBackgroundBitmap.getHeight(), surplusHeight);
            }
            mBackgroundMatrix.postScale(scaleRate, scaleRate);
        } else {
            setMeasuredDimension(Constant.WIDTH_OF_SCREEN, surplusHeight);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawColor(Color.parseColor("#FFFFFF"));
        canvas.drawBitmap(mBackgroundBitmap, mBackgroundMatrix, null);
    }

    /**
     * 设置背景Bitmap
     */
    public void setBackgroundBitmap(Bitmap bitmap) {
        this.mBackgroundBitmap = bitmap;
        invalidate();
    }

    /**
     *  获得设置滤镜后的Bitmap
     */
    public Bitmap getmBackgroundBitmap() {
        return mBackgroundBitmap;
    }
}
